package com.igeek.jdbc.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库操作的工具类
 * 1.获取数据连接
 * 2.释放资源
 */
public class JDBCUtils {

    static String user;
    static String pwd;
    static String url;
    static String driver;

    static{
        //创建Properties类
        Properties properties = new Properties();
        try {
            //加载properties文件
            properties.load(new FileInputStream("src/db.properties"));

            //从properties文件中通过key取值
            user = properties.getProperty("db.user");
            pwd = properties.getProperty("db.pwd");
            url = properties.getProperty("db.jdbcUrl");
            driver = properties.getProperty("db.driverClass");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //获取数据连接对象
    public static Connection getConn(){
        Connection conn = null;
        try {
            //1.加载并注册驱动  Class.forName("全类名")
            Class.forName(driver);

            //2.通过驱动类，获得连接对象，并且返回
            //第一个参数：连接url  账户user  密码password
            conn = DriverManager.getConnection(url,user,pwd);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e){
            e.printStackTrace();
        }

        return conn;
    }



    //释放资源
    public static void close(Connection conn , PreparedStatement ppst , ResultSet rs){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(ppst!=null){
            try {
                ppst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
